package com.bontroller.server;

import java.awt.TrayIcon;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingWorker;

public class WifiHandler extends SwingWorker<String, Object> {

	JLabel addressLab;
	JLabel statusLab;
	JButton cancelBut;
	static final int BUFSIZE = 1024;
	public DatagramSocket socket;
	private static TrayIcon trayIcon;
	TCPServer myTCP;
	String clientSentence = null;
	boolean CONNECTED = true;
	ServerSocket TCPServer;
	FileBrowserServer fileServer;
	private int port;

	public WifiHandler(JLabel address, JButton cancel, TrayIcon tray,
			JLabel status) {
		this.addressLab = address;
		this.cancelBut = cancel;
		trayIcon = tray;
		this.statusLab = status;
		Global.status = 0;

		this.port = Global.port;
	}

	public String doInBackground() {
		this.addressLab.setText("Working");
		String OSName = System.getProperty("os.name");
		if (OSName.contains("Windows"))
			try {
				InetAddress myaddr = InetAddress.getLocalHost();
				String ipAddr = myaddr.getHostAddress();
				this.addressLab.setText(ipAddr);
				if (ipAddr.toString().equals("127.0.0.1"))
					 this.addressLab.setText("No Connection");
			} catch (UnknownHostException localUnknownHostException1) {
			}
		try {
			label280: this.socket = new DatagramSocket(this.port);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Thread tcpThread = new Thread(new TCPServer());
		tcpThread.start();

		this.fileServer = new FileBrowserServer(8889);
		while (true) {
			switch (Global.status) {
			case 0:
				if (Global.btStat)
					break;
				this.statusLab.setText("Disconnected");
				break;
			case 1:
				this.statusLab.setText("Connected");
			}

			if (!tcpThread.isAlive()) {
				tcpThread = new Thread(new TCPServer());
				tcpThread.start();
			}

		}
	}

	public void done() {
		System.out.println("User pressed cancel");
		this.addressLab.setText("Cancelled..");
	}

	public static void trayMessage(String message) {
		trayIcon.displayMessage("Bontroller Server", message,
				TrayIcon.MessageType.INFO);
	}
}